package com.lkbaby.cmd;

import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.CommentEntity;
import org.flowable.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.task.Comment;
import org.flowable.engine.task.Event;

public class MyAddCommentCmd implements Command<Comment> {

	protected String taskId;
	protected String userId;
	protected String processInstanceId;
	protected String type;
	protected String message;

	public MyAddCommentCmd(String taskId, String userId, String processInstanceId, String type, String message) {
		this.taskId = taskId;
		this.userId = userId;
		this.processInstanceId = processInstanceId;
		this.type = type;
		this.message = message;
	}

	@Override
	public Comment execute(CommandContext commandContext) {
		HistoricProcessInstanceEntity hisProIns = null;
		if (processInstanceId != null) {
			hisProIns = CommandContextUtil.getHistoricProcessInstanceEntityManager(commandContext)
					.findById(processInstanceId);
			if (hisProIns == null) {
				throw new FlowableObjectNotFoundException(
						"HistoricProcessInstance " + processInstanceId + " doesn't exist",
						HistoricProcessInstanceEntity.class);
			}
		}
		CommentEntity comment = CommandContextUtil.getCommentEntityManager(commandContext).create();
		comment.setUserId(userId);
		comment.setType(type);
		comment.setTime(CommandContextUtil.getProcessEngineConfiguration(commandContext).getClock().getCurrentTime());
		comment.setTaskId(taskId);
		comment.setProcessInstanceId(processInstanceId);
		comment.setAction(Event.ACTION_ADD_COMMENT);
		// 正则表达式中\s匹配任何空白字符，包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]
		String eventMessage = StringUtils.isNotBlank(message) ? message.replaceAll("\\s+", " ") : "";
		if (eventMessage.length() > 250) {
			eventMessage = eventMessage.substring(0, 250) + "...";
		}
		comment.setMessage(eventMessage);
		comment.setFullMessage(message);
		CommandContextUtil.getCommentEntityManager(commandContext).insert(comment);
		return comment;
	}
}
